// 引入中文翻译js
import MapboxLanguage from "@mapbox/mapbox-gl-language";
// 导入坐标装换js文件
import { bd09_To_gps84, gps84_To_bd09 } from "@/utils/coordConver";
// 导入地图mapboxgl对象
let mapboxgl = require("mapbox-gl/dist/mapbox-gl.js");
// 定义地图对象
let map = {};

// 地图初始化
async function initMap(coordinatesData) {
  mapboxgl.accessToken =
    "申请你的key";
  map = new mapboxgl.Map({
    container: "coordinates",
    style: "mapbox://styles/mapbox/streets-v11",
    center: [99.28840941039061, 27.1848555023209],
    zoom: 12,
    preserveDrawingBuffer: true,
  });
  // 设置语言
  var language = new MapboxLanguage({ defaultLanguage: "zh-Hans" });
  map.addControl(language);
  // 使用定位模块
  map.addControl(
    new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true,
      },
      trackUserLocation: true,
      showUserLocation: true,
      zoom: 14,
    })
  );
  // 加载坐标点
  map.on("load", () => {
    // addMark(coordinatesData);
    // darwLine();
    // 地图边界九段线
    // filterLayers()
  });
  // 给坐标点添加点击事件
  map.on("click", `points`, function (e) {
    e.preventDefault();
    markEvent(e);
  });
}
// 地图增加标记点位
function addMark(data) {
  console.log(data);
  // console.log(markList.find(v=>v.alarmEventName==='管网X007水表').gpsX,markList.find(v=>v.alarmEventName==='管网X007水表').gpsY);
  let markList = JSON.parse(JSON.stringify(data))
  // markList
  markList.forEach((item) => {
    // 百度坐标转换成gps84坐标
    let data = bd09_To_gps84(item.gpsX, item.gpsY);
    item.gpsX = data.lng;
    item.gpsY = data.lat;
    let img = "https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png";
    console.log(item);
    map.loadImage(img, (error, image) => {
      if (error) throw error;
      map.addImage(item.id, image);
      map.addSource(item.id, {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: {
                type: "Point",
                coordinates: [item.gpsX, item.gpsY],
              },
              properties: {
                LyrColor: 1,
                Linetype: "CONTINUOUS",
                Elevation: 0,
                RefName: item.alarmEventName,
                ScaleZ: 1,
                FontID: 1,
                Text: item.address,
                TxtMemo: item.alarmEventName,
                eventId: item.alarmEventName,
              },
            },
          ],
        },
      });
      // Add a symbol layer
      map.addLayer({
        id: item.id,
        type: "symbol",
        source: item.id,
        layout: {
          "icon-image": item.id,
          "text-field": ["get", "RefName"],
          "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
          "text-offset": [0, 1],
          "text-anchor": "top",
          // "icon-size": 0.5,
          "icon-allow-overlap": true,
        },
      });
      //  给点位添加提示框
      map.on("click", item.id, (e) => {
        e.preventDefault();
        // 点位信息
        let showInfo = null;
        // 坐标点位
        let coordinates = [item.gpsX, item.gpsY]; //图片的经纬度
        let res = [{
          keys:'标题1',
          value:'测试1',
        },{
          keys:'标题2',
          value:'测试2',
        }]
          // 拼接模板字符串
          showInfo = `
            <div class="makerTop"  onClick="onMarkJump('${item.address}')">${
            item.alarmEventName
          }</div>
            ${`
            <div>
              ${res.map((item) => {
                  return `<div>${item.keys}&nbsp;:&nbsp;${
                    item.value
                  }</div>`;
                })
                .join("")}
            </div>
            `}
            `;
          new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(showInfo)
            .addTo(map);
      });
      map.on("mouseenter", item.id, function () {
        map.getCanvas().style.cursor = "pointer";
      });
      map.on("mouseleave", item.id, function () {
        map.getCanvas().style.cursor = "";
      });
    });
  });
}

// 地图自定义管网
function darwLine(data) {
  map.addSource("route", {
    type: "geojson",
    data,
  });
  map.addLayer({
    id: "route",
    type: "line",
    source: "route",
    layout: {
      "line-join": "round",
      "line-cap": "round",
    },
    paint: {
      "line-color": {
        type: "categorical",
        property: "Color",
        stops: [
          [84, "#53BC32"],
          [140, "#4ECAF3"],
        ],
      },
      "line-width": 2,
    },
  });
}
// 定义提示框对象
var popup = null;
// 定义图层颜色
let colors = [
  "LightPink",
  "Crimson",
  "PaleVioletRed",
  "HotPink",
  "MediumVioletRed",
  "Orchid",
  "Magenta",
  "MediumPurple",
  "SlateBlue",
  "LightSteelBlue",
];
// 地图自定义图层
function darwFill(data) {
  data.features.forEach((element, index) => {
    map.addLayer({
      id: `${element.properties.Id}Fill`,
      type: "fill",
      source: {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: element.geometry,
            },
          ],
        },
      },
      paint: {
        "fill-color": colors[index],
        "fill-opacity": 0.2,
      },
    });
    map.addLayer({
      id: `${element.properties.Id}Line`,
      type: "line",
      source: {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: element.geometry,
            },
          ],
        },
      },
      paint: {
        "line-color": "#003",
        "line-width": 2,
        "line-opacity": 0.5,
      },
    });
    map.on("click", `${element.properties.Id}Fill`, (e) => {
      popup = createPopup(e, element);
      popup.addTo(map);
      map.setPaintProperty(`${element.properties.Id}Fill`, "fill-opacity", 0.5);
      map.setPaintProperty(`${element.properties.Id}Line`, "line-width", 4);
    });
    map.on("mouseenter", `${element.properties.Id}Fill`, (e) => {
      // popup = createPopup(e, element);
      // console.log("+");
      // popup.addTo(map);
      map.setPaintProperty(`${element.properties.Id}Fill`, "fill-opacity", 0.5);
      map.setPaintProperty(`${element.properties.Id}Line`, "line-width", 4);
    });
    map.on("mouseleave", `${element.properties.Id}Fill`, () => {
      map.setPaintProperty(`${element.properties.Id}Fill`, "fill-opacity", 0.2);
      map.setPaintProperty(`${element.properties.Id}Line`, "line-width", 2);
      // console.log("-");
      // popup.remove();
      // map.fire('closeAllPopups');
    });
  });
}

// 创建popup
function createPopup(e, feature) {
  if (popup) {
    console.log("删除");
    popup.remove();
  }
  // 取区域的颜色
  // let bgc = map.getPaintProperty(`${feature.properties.bigFill}`, "fill-color");
  // let bgc = feature.properties.bigFill;
  // console.log(bgc);

  let html = `<div class="makerTop" onClick="onMarkJump('${feature.properties.dma_name}')">${feature.properties.dma_name}</div>`;
  let newpopup = new mapboxgl.Popup({
    offset: 0,
    closeButton: false,
    className: "popup",
  })
    .setLngLat([e.lngLat.lng, e.lngLat.lat])
    .setHTML(html);
  return newpopup;
}



// 清除标记
function clear(ids) {
  if (Array.isArray(ids)) {
    ids.map((item) => {
      let mySource = map.getSource(item.id);
      if (mySource) {
        map.removeLayer(item.id);
        map.removeSource(mySource.id);
      }
    });
  } else {

    let mySource = map.getSource(ids);
    if (mySource) {
      map.removeLayer(ids);
      map.removeSource(mySource.id);
    }
  }
}
// 获取点击地图坐标
function getLngLat() {
  map.on("click", function (e) {
    if (e.defaultPrevented) return;
    let poi = [];
    // console.log("点击", e.lngLat);
    poi.push(e.lngLat);
    for (let i = 0; i < poi.length; i++) {
      // array.push("[" + poi[i].lng + "," + poi[i].lat + "]")
      // console.log('======');
      console.log("[" + poi[i].lng + "," + poi[i].lat + "],");
      // console.log('======');
      // console.log(array);
    }
    // console.log(that.poi);
    // console.log(array);99.287804,27.196239
  });
}

// 地图边界过滤
function filterLayers() {
  // The "admin-0-boundary-disputed" layer shows boundaries
  // at this level that are known to be disputed.
  map.setFilter('admin-0-boundary-disputed', [
      'all',
      ['==', ['get', 'disputed'], 'true'],
      ['==', ['get', 'admin_level'], 0],
      ['==', ['get', 'maritime'], 'false'],
      ['match', ['get', 'worldview'], ['all', "CN"], true, false]
  ]);
  // The "admin-0-boundary" layer shows all boundaries at
  // this level that are not disputed.
  map.setFilter('admin-0-boundary', [
      'all',
      ['==', ['get', 'admin_level'], 0],
      ['==', ['get', 'disputed'], 'false'],
      ['==', ['get', 'maritime'], 'false'],
      ['match', ['get', 'worldview'], ['all', "CN"], true, false]
  ]);
  // The "admin-0-boundary-bg" layer helps features in both
  // "admin-0-boundary" and "admin-0-boundary-disputed" stand
  // out visually.
  map.setFilter('admin-0-boundary-bg', [
      'all',
      ['==', ['get', 'admin_level'], 0],
      ['==', ['get', 'maritime'], 'false'],
      ['match', ['get', 'worldview'], ['all', "CN"], true, false]
  ]);
}
export default {
  initMap,
  clear,
  addMark,
  darwLine,
  darwFill,
  getLngLat,
  filterLayers
};
